package com.qfedu.vhr.mail;

import com.qfedu.vhr.common.MailBody;
import com.qfedu.vhr.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author baize
 * @date 2023/2/8
 * @site www.qfedu.com
 */
@Component
public class MailConsumer {

    @Autowired
    StringRedisTemplate redisTemplate;


    @RabbitListener(queues = RabbitConfig.EMPLOYEE_MAIL_QUEUE_NAME)
    public void handleMail(Message message, Channel channel) {
        MailBody mailBody = (MailBody) message.getPayload();
        //获取消息的唯一标识符
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        try {
            String key = mailBody.getMsgId();
            String value = redisTemplate.opsForValue().get(key);
            if (value == null || "".equals(value)) {
                //说明这个消息没有被处理过
                System.out.println("邮件发送 = " + mailBody);
                redisTemplate.opsForValue().set(key, key);
                channel.basicAck(deliveryTag, false);

            } else {
                //说明这个消息之前已经处理过了
                System.out.println("重复消息");
                //这个消息是一个重复的消息，直接确认即可，不用发送邮件
                channel.basicAck(deliveryTag, false);
            }

        } catch (IOException e) {
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
